import './less/map.less';
import $ from 'jquery';
import { request, GetQueryString } from "./utils/request";
import { GetScenicSpots, GetToilets, GetMustPlayRoutes, GetPublicFacilities, GetBusinesss, GetTicketPlaces, IsJudgeKey, GetCheckCode, JudgeCheckCode, payRequest, CreateKey,weixinpay,weixinopenid } from "./utils/apis";
import AcIcon from './image/Attractions.png';
import WCc from './image/WCc.png';
import WCo from './image/WCo.png';
import carParkC from './image/carParkC.png';
import carParkO from './image/carParkO.png';
import exitsC from './image/exitsC.png';
import exitsO from './image/exitsO.png';
import trafficC from './image/trafficC.png';
import trafficO from './image/trafficO.png';
import DrinkingC from './image/DrinkingC.png';
import DrinkingO from './image/DrinkingO.png';
import MerchantC from './image/MerchantC.png';
import MerchantO from './image/MerchantO.png';
import TicketC from './image/TicketC.png';
import TicketO from './image/TicketO.png';
import myPosition from './image/myPosition.png';
import goA from './image/goA.png';
import './getCode.js';
$(function () {
    let
        telNum = '',
        keyNum = '',
        codeNum = '',
        myPositionOnload = true,
        gpsWitch = true,
        autoNavPlay = true,
        AllAttractions = [],
        ScenicData = [],
        AllPlayline = [{"$type":"","RPID":"1","RLongitude":117.728816013,"RLatitude":39.151652784},{"$type":"","RPID":"2","RLongitude":117.730190152,"RLatitude":39.1516682506},{"$type":"","RPID":"3","RLongitude":117.730211567,"RLatitude":39.1517253575},{"$type":"","RPID":"4","RLongitude":117.73024369,"RLatitude":39.1517967421},{"$type":"","RPID":"5","RLongitude":117.730293658,"RLatitude":39.1518431408},{"$type":"","RPID":"6","RLongitude":117.730361473,"RLatitude":39.1518788331},{"$type":"","RPID":"7","RLongitude":117.730454272,"RLatitude":39.1518824026},{"$type":"","RPID":"8","RLongitude":117.730572055,"RLatitude":39.1518502797},{"$type":"","RPID":"9","RLongitude":117.730625593,"RLatitude":39.1517931727},{"$type":"","RPID":"10","RLongitude":117.730657716,"RLatitude":39.1517110808},{"$type":"","RPID":"11","RLongitude":117.730661285,"RLatitude":39.15167182},{"$type":"","RPID":"12","RLongitude":117.731296601,"RLatitude":39.15167182},{"$type":"","RPID":"13","RLongitude":117.731332293,"RLatitude":39.1517717572},{"$type":"","RPID":"14","RLongitude":117.731375124,"RLatitude":39.1518467103},{"$type":"","RPID":"15","RLongitude":117.731503614,"RLatitude":39.1519359401},{"$type":"","RPID":"16","RLongitude":117.731585706,"RLatitude":39.1519502168},{"$type":"","RPID":"17","RLongitude":117.731584516,"RLatitude":39.1527604233},{"$type":"","RPID":"18","RLongitude":117.730912616,"RLatitude":39.1530215495},{"$type":"","RPID":"19","RLongitude":117.730347493,"RLatitude":39.1532178553},{"$type":"","RPID":"20","RLongitude":117.730288007,"RLatitude":39.15328329},{"$type":"","RPID":"21","RLongitude":117.730288007,"RLatitude":39.1534082121},{"$type":"","RPID":"22","RLongitude":117.730442672,"RLatitude":39.1536877988},{"$type":"","RPID":"23","RLongitude":117.730609235,"RLatitude":39.1538722065},{"$type":"","RPID":"24","RLongitude":117.730930462,"RLatitude":39.1541220499},{"$type":"","RPID":"25","RLongitude":117.731215997,"RLatitude":39.1544849182},{"$type":"","RPID":"26","RLongitude":117.731382559,"RLatitude":39.1544968154},{"$type":"","RPID":"27","RLongitude":117.731549122,"RLatitude":39.154455175},{"$type":"","RPID":"28","RLongitude":117.731745428,"RLatitude":39.1543956884},{"$type":"","RPID":"29","RLongitude":117.731983373,"RLatitude":39.1544075855},{"$type":"","RPID":"30","RLongitude":117.732197525,"RLatitude":39.1544135337},{"$type":"","RPID":"31","RLongitude":117.732868194,"RLatitude":39.1541566243},{"$type":"","RPID":"32","RLongitude":117.733672791,"RLatitude":39.1538484123},{"$type":"","RPID":"33","RLongitude":117.73380961,"RLatitude":39.1539376421},{"$type":"","RPID":"34","RLongitude":117.733958325,"RLatitude":39.1540030768},{"$type":"","RPID":"35","RLongitude":117.734053504,"RLatitude":39.1540149748},{"$type":"","RPID":"36","RLongitude":117.73420817,"RLatitude":39.1542945614},{"$type":"","RPID":"37","RLongitude":117.734255758,"RLatitude":39.1544849182},{"$type":"","RPID":"38","RLongitude":117.734231964,"RLatitude":39.1546514799},{"$type":"","RPID":"39","RLongitude":117.734112991,"RLatitude":39.1548418367},{"$type":"","RPID":"40","RLongitude":117.733486895,"RLatitude":39.155244581},{"$type":"","RPID":"41","RLongitude":117.733572556,"RLatitude":39.1553873483},{"$type":"","RPID":"42","RLongitude":117.733694622,"RLatitude":39.1554519511},{"$type":"","RPID":"43","RLongitude":117.733887358,"RLatitude":39.1555304728},{"$type":"","RPID":"44","RLongitude":117.734201447,"RLatitude":39.1555447495},{"$type":"","RPID":"45","RLongitude":117.734572643,"RLatitude":39.155516196},{"$type":"","RPID":"46","RLongitude":117.734922424,"RLatitude":39.1555233348},{"$type":"","RPID":"47","RLongitude":117.735243651,"RLatitude":39.1555233348},{"$type":"","RPID":"48","RLongitude":117.735479217,"RLatitude":39.1555090581},{"$type":"","RPID":"49","RLongitude":117.735664816,"RLatitude":39.1553877054},{"$type":"","RPID":"50","RLongitude":117.735871829,"RLatitude":39.1552306613},{"$type":"","RPID":"51","RLongitude":117.735978905,"RLatitude":39.1550093714},{"$type":"","RPID":"52","RLongitude":117.735978905,"RLatitude":39.1547666659},{"$type":"","RPID":"53","RLongitude":117.735850414,"RLatitude":39.154331225},{"$type":"","RPID":"54","RLongitude":117.735871829,"RLatitude":39.1541242119},{"$type":"","RPID":"55","RLongitude":117.735950351,"RLatitude":39.1539528901},{"$type":"","RPID":"56","RLongitude":117.736021735,"RLatitude":39.1537815693},{"$type":"","RPID":"57","RLongitude":117.736021735,"RLatitude":39.1536530786},{"$type":"","RPID":"58","RLongitude":117.73595749,"RLatitude":39.1535245871},{"$type":"","RPID":"59","RLongitude":117.735786169,"RLatitude":39.153367543},{"$type":"","RPID":"60","RLongitude":117.735236513,"RLatitude":39.1532676058},{"$type":"","RPID":"61","RLongitude":117.73511516,"RLatitude":39.1532390523},{"$type":"","RPID":"62","RLongitude":117.73486847,"RLatitude":39.1530334466},{"$type":"","RPID":"63","RLongitude":117.734773291,"RLatitude":39.1528311927},{"$type":"","RPID":"64","RLongitude":117.734612678,"RLatitude":39.1525099657},{"$type":"","RPID":"65","RLongitude":117.734416372,"RLatitude":39.1521946867},{"$type":"","RPID":"66","RLongitude":117.734077299,"RLatitude":39.1519507924},{"$type":"","RPID":"67","RLongitude":117.733916685,"RLatitude":39.1518080241},{"$type":"","RPID":"68","RLongitude":117.733791764,"RLatitude":39.1516474106},{"$type":"","RPID":"69","RLongitude":117.733208795,"RLatitude":39.1516533596},{"$type":"","RPID":"70","RLongitude":117.733196898,"RLatitude":39.1515165404},{"$type":"","RPID":"71","RLongitude":117.733149309,"RLatitude":39.1514035163},{"$type":"","RPID":"72","RLongitude":117.733066028,"RLatitude":39.1513202345},{"$type":"","RPID":"73","RLongitude":117.732947055,"RLatitude":39.1513142864},{"$type":"","RPID":"74","RLongitude":117.732869722,"RLatitude":39.151367824},{"$type":"","RPID":"75","RLongitude":117.732768595,"RLatitude":39.1514748999},{"$type":"","RPID":"76","RLongitude":117.732734986,"RLatitude":39.1516586144},{"$type":"","RPID":"77","RLongitude":117.73187838,"RLatitude":39.1516633727}],
        AllPlaylineIndex = 40,
        AllScenicData = [],
        playLineData = [],
        points = [],
        AllMarket = [],
        AID = GetQueryString("AID")||localStorage.AID,
        ScenicName = GetQueryString("ScenicName")||localStorage.ScenicName,
        MapIndex = null,
        TapIndex = 0,
        playBol = false,
        autoPlayIndex = null,
        AffiliatedChecks = "carParkS&&exitS&&trafficS",
        merchantChecks = "storeS&&DrinkS",
        TicketChecks = "ticketS",
        countI = 0,
        zoom = 17,
        audioPlayIndex = null,
        myPoint2 = {},
        oneMyPoint = {},
        MyPointArr = [],
        AttractionsSearch = '',
        walkingSearchBol = false,
        AttractionsPrice = GetQueryString("AttractionsPrice") ||localStorage.AttractionsPrice ||( JSON.parse(localStorage.Attractions || "{}").Price)|| 10,
        getBsne = {
            lng: '',
            lat: '',
        },
        getBssw = {
            lng: '',
            lat: '',
        },
        wxPayParams = {},
        lastOrientation=0,//上一次角度
        orientationBol=false,//是否支持重力感应
        DrinkSearch = '';
    var audioSetItme = null,
        positionTime = false,
        Attractions = null,
        isGoA = true,
        convertor,
        goAMarket,
        moveendAddTime,
        codeNumTime,
        openid='',
        codeNumT = 60,
        moveendAddEvent = function () {
            //地图移动
            var bs = map.getBounds();   //获取可视区域
            var bssw = bs.getSouthWest();   //可视区域左下角
            var bsne = bs.getNorthEast();   //可视区域右上角

            //分别匹配左下右上的边线多加0.002 预防过早判断
            // console.log(bs);
            // if(goAMarket&&goAMarket.zc){
            // exitAff(map.getCenter(), null, true);
            // }else
            if (getBsne.lng && getBsne.lat && getBssw.lng && getBssw.lat) {
                if ((bssw.lng > (Number(getBsne.lng) + 0.001)) || (bssw.lat > (Number(getBsne.lat) + 0.001)) || (getBssw.lng > (Number(bsne.lng) + 0.001)) || (getBssw.lat > (Number(bsne.lat) + 0.001))) {
                    exitAff(map.getCenter(), null, true);
                } else {
                    if (goAMarket && goAMarket.isVisible()) {
                        goARData()
                    }
                }
            }
        };
    
    // 百度地图API功能
    var myMarker, positionTime;
    map = new BMap.Map("mapContent", { enableMapClick: false });    // 创建Map实例
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 10);  // 初始化地图,设置中心点坐标和地图级别
    // document.getElementsByClassName("activationWrap")[0].style.display="none";
    var myPoint = {},
        htmlWidth = document.documentElement.getBoundingClientRect().width,
        MapSize = (60 * (htmlWidth / 750));
    var geolocation = new BMap.Geolocation();//获取浏览器位置
    var geolocationControl = new BMap.GeolocationControl({
        locationIcon: new BMap.Icon('./image/myPosition.png', new BMap.Size((htmlWidth / 750 * 38), (htmlWidth / 750 * 47))),
    });
    map.addControl(geolocationControl);
    geolocationControl.location();
    var geoc = new BMap.Geocoder();//经纬度转化城市

    var walking = new BMap.WalkingRoute(map, {
        renderOptions: { map: map, autoViewport: true }, onMarkersSet: function (v, o, i) {
            // console.log('Markerset',walking.getResults(),walking.getResults().getStart())
            // map.removeOverlay(walking.getResults().getStart())
            // map.removeOverlay(walking.getResults().getEnd())
            map.getOverlays().map((item) => {
                // console.log(item.getTitle && item.getTitle())
                if (item.getTitle && (item.getTitle() == "起点" || item.getTitle() == "终点")) {
                    map.removeOverlay(item);
                }
            })
        }
    });
    // walking.setPolylinesSetCallback(function (res) {
    //     // console.log(res)
    // })
    var startX = 0, startY = 0;
    $(".app>.AttractionsList,.app>.DrinkList,.app>.AffiliatedList").on('touchmove', (e) => { e.stopPropagation() });
    $(".app>.AttractionsList div.list,.app>.DrinkList div.list,.app>.AffiliatedList div.list").on('touchstart', function (ev) {
        try {
            //evt.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等
            var touch = ev.touches[0]; //获取第一个触点
            var x = Number(touch.clientX); //页面触点X坐标
            var y = Number(touch.clientY); //页面触点Y坐标
            //记录触点初始位置
            startX = x;
            startY = y;

        } catch (e) {
            // console.log(e)
            // alert('touchSatrtFunc：' + e.message);
        }

    });
    $(".app>.AttractionsList div.list,.app>.DrinkList div.list,.app>.AffiliatedList div.list").on('touchmove', function (ev) {
        var _ss = ev.currentTarget;

        var _point = ev.touches[0],
            _top = _ss.scrollTop;
        // 什么时候到底部
        var _bottomFaVal = _ss.scrollHeight - _ss.offsetHeight;
        // console.log(startY, _point.clientY)
        if (_ss.scrollHeight <= _ss.offsetHeight || (_top == 0 && startY < _point.clientY) || (_top === _bottomFaVal && startY > _point.clientY)) {
            ev.preventDefault();
        }
        ev.stopPropagation();
    });
    if (ScenicName&&ScenicName!=null) {
        //设置标题
        $(".footer .sitePosition .ScenicName").html(ScenicName);
        setTitle(ScenicName);
    };

    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/Android/i) == "android" && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var latitudeP = position.coords.latitude,
                longitudeP = position.coords.longitude;
            var points = wgs2bd(Number(latitudeP), Number(longitudeP));
            getMyPoint({ point: { lng: points[1], lat: points[0] } })
            var timer = navigator.geolocation.watchPosition(function (position) {
                var latitudeP = position.coords.latitude,
                    longitudeP = position.coords.longitude;
                var points = wgs2bd(Number(latitudeP), Number(longitudeP));
                getMyPoint({ point: { lng: points[1], lat: points[0] } })
            }, function (err) {
                switch (err.code) {
                    case 1:
                        alert("用户拒绝定位请问");
                        break;

                    case 2:
                        alert("暂时获取不到位置信息");
                        break;

                    case 3:
                        alert("请求超时");
                        break;

                    case 4:
                        alert("未知错误");
                        break;
                }
                $(".mapComponent .gpsWitch").attr('class', 'gpsWitch open2')
                navigator.geolocation.clearWatch(timer); //关闭定位请求
            }, {
                    enableHighAcuracy: true,
                    timeout: 2000,
                    maximumAge: 1000,
                    frequency: 100000
                });
        }, function (err) {
            switch (err.code) {
                case 1:
                    alert("用户拒绝定位请问");
                    break;

                case 2:
                    alert("暂时获取不到位置信息");
                    break;

                case 3:
                    alert("请求超时");
                    break;

                case 4:
                    alert("未知错误");
                    break;
            }
            $(".mapComponent .gpsWitch").attr('class', 'gpsWitch open2')
        }, {//单次请求设置，避免多次请求
                enableHighAcuracy: true,//更精确的查找
                timeout: 2000,//获取位置允许最长时间
                maximumAge: 100//位置可以缓存的最大时间，
            });

    } else {
        positionTime = true;
        getMylocation();

    }

    // geolocationControl.addEventListener("locationSuccess", getMyPoint,{enableHighAccuracy:true,maximumAge:100});
    // geolocationControl.addEventListener("locationError",function(e){
    // 定位失败事件
    // alert(e.message);
    // });




    if ((localStorage.JudgeKeyArr && localStorage.JudgeKeyArr.indexOf(AID) >= 0) || AttractionsPrice == 0) {
    } else {
        $(".activationWrap").show();
    }


    convertor = new BMap.Convertor();

    Attractions = JSON.parse(localStorage.Attractions || '{}');
    $('.map .head').show();
    $(".activationWrap .activationBox .activBox .buy").text(`在线购买${AttractionsPrice}元`)
    // 激活手机号
    var pattern = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
    $(".activationWrap .activationBox .tel input").bind("input", function (e) {
        telNum = e.target.value;
        if (pattern.test(telNum) && keyNum.length > 1) {
            $("div.activationWrap div.button").attr("class", "button ok")
        } else {
            $("div.activationWrap div.button").attr("class", "button")
        }
    });
    //激活key
    $(".activationWrap .activationBox .key input").bind("input", function (e) {
        keyNum = e.target.value;
        if (pattern.test(telNum) && keyNum.length > 1) {
            $("div.activationWrap div.button").attr("class", "button ok")
        } else {
            $("div.activationWrap div.button").attr("class", "button")
        }
    });
    //验证码
    $(".activationWrap .activationBox .code input").bind("input", function (e) {
        codeNum = e.target.value;
    });
    $(".activationWrap .activationBox .exit").click(function () {
        $(".activationWrap").hide();
        var JudgeKeyArr = localStorage.JudgeKeyArr;
        if ((JudgeKeyArr) && (!(JudgeKeyArr.indexOf(AID) >= 0))) {
            var JudgeKeyAll = JSON.parse(JudgeKeyArr);
            JudgeKeyAll.push(AID);
            localStorage.JudgeKeyArr = JSON.stringify(JudgeKeyAll)
        } else if (!JudgeKeyArr) {
            localStorage.JudgeKeyArr = JSON.stringify([AID]);
        }
    })
    $(".activationWrap .activationBox .buy").click(function () {
        //在线购买
        $(".activationWrap .activationBox .activBox").hide()
        $(".activationWrap .activationBox .buyBox").show();
    })
    $(".activationWrap .activationBox .buyBox .confirmBuy").click(function () {
        
        if (pattern.test(telNum) && codeNum > 0) {
            request(JudgeCheckCode, { MobilePhone: telNum, CheckCode: codeNum }, (result) => {
                // console.log("result", result)
                if (result[0]['Return'] == "True") {
                    if(navigator.userAgent.indexOf("MicroMessenger/")>=0){
                        if(localStorage.openid&&localStorage.openid.length>0){
                            getWXCode();
                        }else{
                            console.log("未获取到用户openID")
                        }
                    }else{
                        tipsShow("请在微信浏览器进行支付")
                    }
                    //进行微信支付
                }
                // request(CreateKey,{AID,MobilePhone:telNum},(result)=>{
                //     if(result[0]['Key']){
                //         //生成key成功
                //     }
                // })

            }, (result) => { }, "post")
        }
    })
    $(".activationWrap .activationBox .buyBox .codeNum").click(function (e) {
        // 获取验证码
        if (codeNumT !== 60) return;
        $(e.target).attr("class", "codeNum disabled");
        $(e.target).text(codeNumT)
        codeNumTime = setInterval(function () {
            codeNumT--;
            $(e.target).text(codeNumT)
            if (codeNumT <= 0) {
                codeNumT = 60;
                clearInterval(codeNumTime);
                $(e.target).text("获取验证码")
                $(e.target).attr("class", "codeNum");
            }
        }, 1000)
        if (pattern.test(telNum)) {
            request(GetCheckCode, { MobilePhone: telNum }, (result) => {
                // console.log("result", result)
                tipsShow("发送成功")
                if (result[0]['Return'] == "True") {
                }
            }, (result) => { }, "post")
        } else {
            tipsShow("请输入手机号码！");
        }
    })

    $(".activationWrap .activationBox .button").click(function () {
        if (AID && telNum.length == 11 && keyNum.length > 1) {
            request(IsJudgeKey, { AID, KEY: keyNum, MobilePhone: telNum }, (result) => {
                if (result[0] && result[0].Return === "True") {
                    $(".activationWrap").hide();
                    var JudgeKeyArr = localStorage.JudgeKeyArr;
                    if ((JudgeKeyArr) && (!(JudgeKeyArr.indexOf(AID) >= 0))) {
                        var JudgeKeyAll = JSON.parse(JudgeKeyArr);
                        JudgeKeyAll.push(AID);
                        localStorage.JudgeKeyArr = JSON.stringify(JudgeKeyAll)
                    } else if (!JudgeKeyArr) {
                        localStorage.JudgeKeyArr = JSON.stringify([AID]);
                    }
                } else {
                    tipsShow("手机号或者key码错误")
                }
            }, (result) => {

            }, "post");
        }
    })
    $(".mapComponent .gpsWitch,.mapComponent .gpsBox .gpsSet").click(function (e) {
        //智能导游弹窗
        e.stopPropagation();
        $(".mapComponent .gpsBox").show();
    });

    $(".mapComponent .gpsBox,.mapComponent .gpsBox .gpsSet .setHead .close").click(function (e) {
        //智能导游弹窗关闭
        e.stopPropagation();
        $(".mapComponent .gpsBox").hide();
    });

    $(".ExitNavigation").click(function () {
        //退出导航

        $(".ExitNavigation").hide();
        walkingSearchBol = false;
        switch (TapIndex) {
            case 0:
                $(".app .footer .sitePosition").show();
                break;
            case 1:
                clearWcIcon();
                $(".app .footer .sitePosition").show();
                break;
            case 2:
                $(".app .footer .sitePosition").show();
                var pointsP = playLineData.map((item) => item.points);
                var polyline = new BMap.Polyline(pointsP, { strokeColor: "#1a9bff", strokeWeight: 4, strokeStyle: "dashed", strokeOpacity: 1, enableClicking: false });   //创建折线
                map.addOverlay(polyline);
                break;
            case 3:
                clearFacilityIcon();
                $(".app .map .sitePositionAffiliated").show();
                break;
            case 4:
                clearDrinkIcon();
                $(".app .map .sitePositionDrink").show();
                break;
            case 5:
                clearTicketIcon();
                // $(".app .map .sitePositionTicket").show();
                $(".app .footer .sitePosition").show();
                break;
        }
        walking.clearResults();
        var item = (TapIndex == 2 ? AllAttractions : ScenicData)[MapIndex];
        map.setZoom(zoom);
        map.panTo(item.points)
    });

    $(".mapComponent .gpsBox .gpsSet .setBox .checkbox i").click(function (e) {
        autoNavPlay = !autoNavPlay;
        gpsWitch = !gpsWitch;
        $(e.target).attr('class', !autoNavPlay ? "checkboxC" : "checkboxO");
        $(".mapComponent .gpsWitch").attr('class', 'gpsWitch ' + (gpsWitch ? "open" : ""))
        // autoAudioPlay(autoPlayIndex);

    });

    $(".footer .AttractionsInfo .explain").click(function (e) {
        //解说按钮
        var className = e.target.className;
        if (className.indexOf('play') >= 0) {
            audioPause();
            $(".footer .AttractionsInfo .explain").attr('class', 'explain pause');
        } else {
            audioPlay();
        }
    });
    $(".footer .AttractionsInfo .info>div").click(function (e) {
        //进入景点详情
        // console.log(ScenicData[MapIndex])
        attractionShow();
    });
    $(".app>.AttractionsInfo .img .linkMap").click(function () {
        //进入地图
        $(".app>div").hide();
        $(".app>.map").show();
        $(".app .footer >div").hide();
        $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();
    });
    $(".app>.AttractionsInfo .before").click(function () {
        //上一个音频
        if (MapIndex > 0) {
            MapIndex--;
            attractionShow();
            // audioPlay();
        }
    });
    $(".app>.AttractionsInfo .after").click(function () {
        //下一个音频
        if (MapIndex < ScenicData.length - 1) {
            MapIndex++;
            attractionShow();
            // audioPlay();
        }
    });
    $(".app>.AttractionsInfo .audioPack .autoControlStrip .play").click(function () {
        //播放暂停
        if (playBol) {
            audioPause();
        } else {
            audioPlay();
        }
    })
    $("#AttractionsAudio").get(0).addEventListener('ended', function () {
        //播放结束
        // console.log('audio ended')
        $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-play1');
        $(".footer .AttractionsInfo .explain").attr('class', 'explain');
        autoPlayIndex = null;
        // autoAudioPlay(autoPlayIndex + 1);
        // autoNavPlay = false;
    });
    $(".footer .sitePosition .position,.footer .sitePositionDrink .position,.footer .sitePositionAffiliated .position,.footer .sitePositionTicket .position").click(function (e) {
        //定位
        if (myPoint.lng) {
            // console.log(myPoint)
            map.panTo(myPoint, 12);
        }
    })

    $(".footer .sitePosition .siteInfo .open").click(function (e) {
        //列表
        $(".app .footer .sitePosition").hide();
        $(".AttractionsList").show();
    })
    $(".AttractionsList .title .icon-listClose").click(function () {
        $(".AttractionsList").hide();
        $(".app .footer .sitePosition").show();
    });

    $(".AttractionsList .search input").bind("input", function (e) {
        //景点搜索
        // console.log(e.target.value,TapIndex);
        AttractionsSearch = e.target.value;
        if (TapIndex == 0) {
            setAttractionsList()
        } else if (TapIndex == 2) {
            setPlayAttractionsList()
        }
    });
    $(".DrinkList .search input").bind("input", function (e) {
        //商家搜索
        // console.log(e.target.value,TapIndex);
        DrinkSearch = e.target.value;
        setDrinkingList()
    });
    $(".DrinkList .title .food").click(function () {
        //餐饮icon
        if (merchantChecks.indexOf('DrinkS') >= 0) {
            merchantChecks = merchantChecks.replace('DrinkS', 'Drink')
            $(".DrinkList .title .food i").attr('class', 'icon-checkBoxC2');
        } else {
            merchantChecks = merchantChecks.replace('Drink', 'DrinkS');
            $(".DrinkList .title .food i").attr('class', 'icon-checkBoxO2');
        }
        setDrinkingList();
    })
    $(".DrinkList .title .store").click(function () {
        //商店icon
        if (merchantChecks.indexOf('storeS') >= 0) {
            merchantChecks = merchantChecks.replace('storeS', 'store')
            $(".DrinkList .title .store i").attr('class', 'icon-checkBoxC2');
        } else {
            merchantChecks = merchantChecks.replace('store', 'storeS');
            $(".DrinkList .title .store i").attr('class', 'icon-checkBoxO2');
        }
        setDrinkingList();
    })
    $(".DrinkList .title .icon-listClose").click(function () {
        //收起列表
        $(".DrinkList").hide();
        $(".footer .sitePositionDrink").show();
    })
    $(".footer .sitePositionDrink .siteInfo .open").click(function () {
        //打开列表
        $(".footer .sitePositionDrink").hide();
        $(".DrinkList").show();
    })

    $(".AffiliatedList .title .exit").click(function () {
        //出入口icon
        if (AffiliatedChecks.indexOf('exitS') >= 0) {
            AffiliatedChecks = AffiliatedChecks.replace('exitS', 'exit')
            $(".AffiliatedList .title .exit i").attr('class', 'icon-checkBoxC2');
        } else {
            AffiliatedChecks = AffiliatedChecks.replace('exit', 'exitS');
            $(".AffiliatedList .title .exit i").attr('class', 'icon-checkBoxO2');
        }
        setAffiliatedList();
    })

    $(".AffiliatedList .title .traffic").click(function () {
        //交通icon
        if (AffiliatedChecks.indexOf('trafficS') >= 0) {
            AffiliatedChecks = AffiliatedChecks.replace('trafficS', 'traffic')
            $(".AffiliatedList .title .traffic i").attr('class', 'icon-checkBoxC2');
        } else {
            AffiliatedChecks = AffiliatedChecks.replace('traffic', 'trafficS');
            $(".AffiliatedList .title .traffic i").attr('class', 'icon-checkBoxO2');
        }
        setAffiliatedList();
    })

    $(".AffiliatedList .title .carPark").click(function () {
        //停车场icon
        if (AffiliatedChecks.indexOf('carParkS') >= 0) {
            AffiliatedChecks = AffiliatedChecks.replace('carParkS', 'carPark')
            $(".AffiliatedList .title .carPark i").attr('class', 'icon-checkBoxC2');
        } else {
            AffiliatedChecks = AffiliatedChecks.replace('carPark', 'carParkS');
            $(".AffiliatedList .title .carPark i").attr('class', 'icon-checkBoxO2');
        }
        setAffiliatedList();
    })
    $(".AffiliatedList .title .icon-listClose").click(function () {
        $(".AffiliatedList").hide();
        $(".footer .sitePositionAffiliated").show();
    })
    $(".footer .sitePositionAffiliated .siteInfo .open").click(function () {
        $(".footer .sitePositionAffiliated").hide();
        $(".AffiliatedList").show();
    })

    $(".TicketList .title .Ticket").click(function () {
        //售票处icon
        if (TicketChecks.indexOf('ticketS') >= 0) {
            TicketChecks = TicketChecks.replace('ticketS', 'ticket')
            $(".TicketList .title .Ticket i").attr('class', 'icon-checkBoxC2');
        } else {
            TicketChecks = TicketChecks.replace('ticket', 'ticketS');
            $(".TicketList .title .Ticket i").attr('class', 'icon-checkBoxO2');
        }
        setTicketList();
    })
    $(".TicketList .title .icon-listClose").click(function () {
        $(".TicketList").hide();
        $(".footer .sitePositionTicket").show();
    })
    $(".footer .sitePositionTicket .siteInfo .open").click(function () {
        $(".footer .sitePositionTicket").hide();
        $(".TicketList").show();
    })


    $(".app .footer .AttractionsInfo>.nav").click(function (e) {
        //景点导航
        var item = (TapIndex == 2 ? AllAttractions : ScenicData)[MapIndex];
        walking.search(myPoint, item['points']);
        $(".app .footer >div").hide();
        // $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();
        $(".app .footer .siteInfo .ScenicName").text(item.SNAME);
        $(".app .footer .siteInfo .distance").text(item.km + "km");
        $(".ExitNavigation").show();
        walkingSearchBol = true;
    });
    $(".app .footer .WCNavInfo .nav").click(function (e) {
        //其他导航
        var item = ScenicData[MapIndex];
        walking.search(myPoint, item['points'])
        $(".app .footer >div").hide();
        walkingSearchBol = true;
        $(".ExitNavigation").show();
    });
    $(".map .head .tapList>div").click(function (e) {
        if (TapIndex !== $(e.target).index()) {
            walking.clearResults();
            map.setZoom(zoom);
            audioPlayIndex = null;
            autoPlayIndex = null;

            var left = $(".map .head .tapList").scrollLeft() + $(e.target).offset().left - (htmlWidth / 2) + ($(e.target).width() / 2);
            // console.log($(e.target).offset(),left, $(e.target).index())
            $(".map .head .tapList").scrollLeft(left);

        }
        TapIndex = $(e.currentTarget).index();
        map.clearOverlays();
        $(".map .head .tapList>div").attr('class', '');
        $(".map .head .tapList>div").eq(TapIndex).attr('class', 'active');
        $(".app .footer >div").hide();
        $(".app >div:not(.map)").hide();
        $(".DrinkList .search input,.AttractionsList .search input").val('');
        countI = 0;
        // MapIndex = null;
        DrinkSearch = "";
        AttractionsSearch = "";
        switch (TapIndex) {
            case 0://景点游玩
                $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();
                AID && request(GetScenicSpots, { AID }, (result) => {
                    ScenicData = result;
                    // ScenicData.map((item, index) => {
                    //     setMapCenter({ lng: item["SLNG"], lat: item["SLAT"] }, index, item.SPIC, item['SNAME']);
                    // })
                    var points = ScenicData.map((item, index) => {
                        return { lng: Number(item["SLNG"]) || 0, lat: Number(item["SLAT"]) || 0 }
                    })
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        setMapCenter(new BMap.Point(item.lng, item.lat), index, ScenicData[index]['SPIC'], ScenicData[index]['SNAME']);
                    })
                    AllScenicData = ScenicData;
                }, () => { }, "post");
                break;
            case 1://洗手间
                $(".app .footer .sitePosition").show();
                $(".footer .sitePosition .siteInfo").hide();
                AID && request(GetToilets, { AID }, (result) => {
                    ScenicData = result;
                    // ScenicData.map((item, index) => {
                    //     setMapCenterWC({ lng: item["FLNG"], lat: item["FLAT"] }, index, WCc)
                    // })
                    var points = ScenicData.map((item, index) => {
                        return { lng: Number(item["FLNG"]) || 0, lat: Number(item["FLAT"]) || 0 }
                    })
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        setMapCenterWC(new BMap.Point(item.lng, item.lat), index, WCc);
                    })
                }, () => { }, "post");
                break;
            case 2://必玩清单
                $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();

                AllAttractions = AllScenicData.map((item) => {
                    // console.log(item)
                    if (item['isMust'] == 1) return item;
                    return false
                }).filter(item => item);
                AllAttractions.map((item, index) => {
                    setMapCenterMPR(item, index);
                })
                AID && request(GetMustPlayRoutes, { AID }, (result) => {
                    playLineData = result;
                    var points = playLineData.map((item, index) => {
                        return { lng: Number(item["RLongitude"]) || 0, lat: Number(item["RLatitude"]) || 0 }
                    })
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        setPlayLine(new BMap.Point(item.lng, item.lat), index);
                    })
                    // playLineData.map((item, i) => {
                    //     setPlayLine(item, i);
                    // })
                }, () => { }, "post");
                break;
            case 3://附属设施
                $(".footer>div.sitePositionAffiliated").show();
                AID && request(GetPublicFacilities, { AID }, (result) => {
                    ScenicData = result;
                    var points = ScenicData.map((item, index) => {
                        return { lng: Number(item["FLNG"]) || 0, lat: Number(item["FLAT"]) || 0 }
                    });
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        var FType = ScenicData[index]['FType'];
                        var SPIC = FType === "出入口" ? exitsC : (FType === "停车场" ? carParkC : trafficC);
                        setMapCenterP(new BMap.Point(item.lng, item.lat), index, SPIC);
                    })
                    // ScenicData.map((item, index) => {
                    //     setMapCenterP({ lng: item["FLNG"], lat: item["FLAT"] }, index, SPIC);
                    // })
                }, () => { }, "post");
                break;
            case 4://商家
                $(".footer>div.sitePositionDrink").show();
                AID && request(GetBusinesss, { AID }, (result) => {
                    ScenicData = result;
                    var points = ScenicData.map((item, index) => {
                        return { lng: Number(item["FLNG"]) || 0, lat: Number(item["FLAT"]) || 0 }
                    });
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        var FType = ScenicData[index]['FType'];
                        var SPIC = FType === "商店" ? MerchantC : DrinkingC;
                        setMapCenterDrink(new BMap.Point(item.lng, item.lat), index, SPIC);
                    })
                    // ScenicData.map((item, index) => {
                    //     var SPIC = item.FType === "商店" ? MerchantC : DrinkingC;
                    //     setMapCenterDrink({ lng: item["FLNG"], lat: item["FLAT"] }, index, SPIC);
                    // });
                }, () => { }, "post");
                break;
            case 5://售票处
                // $(".footer >div.sitePositionTicket").show();
                $(".app .footer .sitePosition").show();
                $(".footer .sitePosition .siteInfo").hide();
                AID && request(GetTicketPlaces, { AID }, (result) => {
                    ScenicData = result;
                    var points = ScenicData.map((item, index) => {
                        return { lng: Number(item["FLNG"]) || 0, lat: Number(item["FLAT"]) || 0 }
                    });
                    var bPoints = GpsToBaiduPoints(points);
                    bPoints.map((item, index) => {
                        setMapCenterTicket(new BMap.Point(item.lng, item.lat), index, TicketC);
                    })
                    // ScenicData.map((item, index) => {
                    //     setMapCenterTicket({ lng: item["FLNG"], lat: item["FLAT"] }, index, TicketC);
                    // })
                }, () => { }, "post");
                break;
        }
        // console.log(ScenicData)
    })
    map.addEventListener("click", function (e) {
        //地图点击事件
        switch (TapIndex) {
            case 0:
                $(".app>.AttractionsList,.app .footer >div:not(.ExitNavigation)").hide();
                $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();
                break;
            case 1:
                $(".app .footer >div:not(.ExitNavigation)").hide();
                $(".app .footer .sitePosition").show();
                if ($(".ExitNavigation").is(":hidden")) clearWcIcon();
                break;
            case 2:
                $(".app>.AttractionsList,.app .footer >div:not(.ExitNavigation)").hide();
                $(".app .footer .sitePosition,.app .footer .sitePosition .siteInfo").show();
                break;
            case 3:
                $(".app>div:not(.map),.app .footer >div:not(.ExitNavigation)").hide();
                $(".footer>div.sitePositionAffiliated").show();
                if ($(".ExitNavigation").is(":hidden")) clearFacilityIcon();
                break;
            case 4:
                $(".app>div:not(.map),.app .footer >div:not(.ExitNavigation)").hide();
                $(".footer>div.sitePositionDrink").show();
                if ($(".ExitNavigation").is(":hidden")) clearDrinkIcon();
                break;
            case 5:
                // $(".app>div:not(.map),.app .footer >div:not(.ExitNavigation)").hide();
                // $(".footer>div.sitePositionTicket").show();
                $(".app .footer >div:not(.ExitNavigation)").hide();
                $(".app .footer .sitePosition").show();
                if ($(".ExitNavigation").is(":hidden")) clearTicketIcon();
                break;
        }
    });

    function exitAff(points, km, bol) {
        if ((!ScenicData[0]) || walkingSearchBol) return;
        var points = points ? points : map.getCenter();
        var km = km ? km : (Number((map.getDistance(myPoint, points)) || 0) / 1000).toFixed(2);
        // console.log(Attractions,km)
        if ((km > 10 && isGoA) || bol) {
            // console.log(bol)
            if (!bol) {

                if (km > 900) map.setZoom(5);
                else if (km > 700) map.setZoom(6);
                else if (km > 500) map.setZoom(7);
                else if (km > 300) map.setZoom(8);
                else if (km > 200) map.setZoom(9);
                else if (km > 100) map.setZoom(10);
                else if (km > 50) map.setZoom(11);
                else if (km > 30) map.setZoom(12);
                else if (km > 20) map.setZoom(13);
                else if (km > 10) map.setZoom(14);
            }
            if (!(goAMarket)) {
                var myIcon = new BMap.Icon(goA, new BMap.Size(((htmlWidth / 750) * 96), ((htmlWidth / 750) * 96)));
                goAMarket = new BMap.Marker(points, { icon: myIcon, enableMassClear: false });
                map.addOverlay(goAMarket);
                // map.removeEventListener('moveend', moveendAddEvent);
                goAMarket.addEventListener('click', function () {
                    // map.setZoom(zoom);
                    isGoA = false;
                    goARData();
                    // setTimeout(function () {
                    //     map.addEventListener('moveend', moveendAddEvent);
                    // }, 100);
                })
                map.addOverlay(goAMarket);
                setTimeout(function () {
                    goAMarket.zc && (goAMarket.zc.className = 'BMap_Marker goA');
                }, 20);
            } else if(!(goAMarket&&goAMarket.isVisible())){
                goAMarket.show();
                goAMarket.setPosition(points);
            }else {
                goAMarket.setPosition(points);
            }
            
        }
    }

    function getMylocation() {
        //获取自己位置
        geolocation.getCurrentPosition(getMyPoint, { enableHighAccuracy: true, maximumAge: 0, timeout: 500 });
    }
    function getAngle(px,py,mx,my){//获得人物中心和鼠标坐标连线，与y轴正半轴之间的夹角
        var x = Math.abs(px-mx);
        var y = Math.abs(py-my);
        var z = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
        var cos = y/z;
        var radina = Math.acos(cos);//用反三角函数求弧度
        var angle = Math.floor(180/(Math.PI/radina));//将弧度转换成角度

        if(mx>px&&my<py){//鼠标在第四象限
            angle = 180 - angle;
        }

        if(mx==px&&my<py){//鼠标在y轴负方向上
            angle = 180;
        }

        if(mx>px&&my==py){//鼠标在x轴正方向上
            angle = 90;
        }

        if(mx<px&&my<py){//鼠标在第三象限
            angle = 180+angle;
        }

        if(mx<px&&my==py){//鼠标在x轴负方向
            angle = 270;
        }

        if(mx<px&&my>py){//鼠标在第二象限
            angle = 360 - angle;
        }



            return angle;
    }
    function getMyPoint(e) {
        // 定位成功事件
        // console.log(e.accuracy)

        var lat = AllPlayline[AllPlaylineIndex]['RLatitude'];
        var lng = AllPlayline[AllPlaylineIndex]['RLongitude'];
        var point = wgs2bd(Number(lat)||0,Number(lng)||0);
        if(AllPlaylineIndex>=AllPlayline.length-1){
            AllPlaylineIndex = 12;
        }else{
            AllPlaylineIndex++;
        }

        var lowPoint = new BMap.Point(myPoint.lng || e.point.lng, myPoint.lat || e.point.lat);
        myPoint = new BMap.Point(point[1], point[0]);
        // console.log(myPoint,point)
        // myPoint = new BMap.Point(e.point.lng, e.point.lat);
        // if(e.accuracy >100){
            //精准度
        // }
        // console.log('locationSuccess',e,e.point,myPoint)
        if (myMarker) {
            // myPoint = new BMap.Point(117.74391461338,39.16148867398);

            if(!orientationBol){
                //不支持重力，使用坐标判断方向
                var x1 = lowPoint.lng, x2 = myPoint.lng; //点2坐标
                var y1 = lowPoint.lat, y2 = myPoint.lat; //点1坐标;
                var jiaodu = getAngle(x1,y1,x2,y2)||0;
                var Distance = map.getDistance(myPoint, myPoint2);
            }

            var Distance2 = map.getDistance(myPoint, oneMyPoint);
            if (myPoint.lat > (Number(getBssw.lat) - 0.003) && myPoint.lat < (Number(getBsne.lat) + 0.003) && myPoint.lng > (Number(getBssw.lng) - 0.003) && myPoint.lng < (Number(getBsne.lng) + 0.003)) {
                // console.log('ok')
            } else {
                // (isGoA) && exitAff();
            }
            if (Distance > 30) {
                myPoint2 = new BMap.Point(myPoint.lng || e.point.lng, myPoint.lat || e.point.lat);
                switch (TapIndex) {
                    case 0:
                        ScenicData = ScenicData.map((item, index) => {
                            item.mm = ((Number(map.getDistance(myPoint, item.points)) || 0)).toFixed(2);
                            item.km = ((Number(map.getDistance(myPoint, item.points)) || 0) / 1000).toFixed(2);
                            return item;
                        });
                        setAttractionsList();
                        break;
                    case 2:
                        AllAttractions = AllAttractions.map((item, index) => {
                            item.km = ((Number(map.getDistance(myPoint, item.points)) || 0) / 1000).toFixed(2);
                            item.mm = ((Number(map.getDistance(myPoint, item.points)) || 0)).toFixed(2);
                            return item;
                        });
                        setPlayAttractionsList();
                        break;
                    case 3:
                        setAffiliatedList(true);
                        break;
                    case 4:
                        setDrinkingList(true);
                        break;
                    case 5:
                        // setTicketList(true);
                        break;
                }
            }
            if(!orientationBol){
                myMarker.setRotation(jiaodu);
            }
            myMarker.setPosition(myPoint);

        } else {
            if (myPositionOnload) {
                
                (AID) && request(GetScenicSpots, { AID }, (result) => {
                    // console.log(typeof result)
                    ScenicData = result;
                    AllScenicData = ScenicData;
                    if (myPositionOnload) {
                        var points = ScenicData.map((item, index) => {
                            // setMapCenter({ lng: item["SLNG"], lat: item["SLAT"] }, index, item.SPIC, item['SNAME'])
                            return { lng: Number(item["SLNG"]) || 0, lat: Number(item["SLAT"]) || 0 }
                        })
                        var bPoints = GpsToBaiduPoints(points);
                        bPoints.map((item, index) => {
                            setMapCenter(new BMap.Point(item.lng, item.lat), index, ScenicData[index]['SPIC'], ScenicData[index]['SNAME']);
                        })
                        myPositionOnload = false;
                        AllScenicData = ScenicData;
                    }
                }, () => { }, "post");
                // if(ScenicData){
                //     ScenicData.map((item, index) => {
                //         setMapCenter({ lng: item["SLNG"], lat: item["SLAT"] }, index, item.SPIC, item['SNAME'])
                //     });
                // }
                // myPositionOnload= false;
            } else {
                // myPositionOnload= true;
                // myPoint = new BMap.Point(117.01516848911,39.141374850601);
            }
            // map.centerAndZoom(myPoint, 17);
            // map.panTo(myPoint);

            map.setZoom(zoom);
            // map.addEventListener('addoverlay',setClassName)
            var size = new BMap.Size(0, -(htmlWidth / 750) * 8);
            var myIcon = new BMap.Icon(myPosition, new BMap.Size(((htmlWidth / 750) * 38), ((htmlWidth / 750) * 47)));
            myMarker = new BMap.Marker(myPoint, { icon: myIcon, enableMassClear: false, offset: size });
            map.addOverlay(myMarker);
            
            // console.log(myMarker.getMap())
            // myMarker.getMap().zc.className = 'BMap_Marker myPosition'
            setTimeout(function () {
                myMarker.zc && (myMarker.zc.className = 'BMap_Marker myPosition');
            }, 20);
            myPoint2 = myPoint;
            oneMyPoint = myPoint;
        　　if (window.DeviceMotionEvent) {
                //判断是否支持重力感应，如果支持每10度重新调整角度
                // console.log('deviceorientation')
                window.addEventListener('deviceorientation', function(event) {
                    var compassdir;
                    if(event.webkitCompassHeading) {
                    // Apple works only with this, alpha doesn't work
                    compassdir = event.webkitCompassHeading;  
                    }
                    else compassdir = event.alpha;
                    if((Math.abs(compassdir-lastOrientation)>10)&&(Math.abs(compassdir-lastOrientation)<350)){

                        myMarker.setRotation(parseInt(compassdir)*(-1))
                        // console.log('compassdir',compassdir)
                        lastOrientation = compassdir;
                    }

                });
            }else{
                orientationBol = false;
            }
            // map.removeEventListener('addoverlay',setClassName)
            map.addEventListener('tilesloaded', maptilesloaded);
        }
        //   alert("当前定位地址为：" + address);
        if (positionTime&&(/iphone|ipad|ipod/).test(ua)){
            setTimeout(() => {
                // geolocationControl.location();
                getMylocation();
            }, 500)
        }
    }
    function setClassName(e){
        // console.log('setClassName',e)
        // myMarker.zc && (myMarker.zc.className = 'BMap_Marker myPosition');
        // e.target.zc && (e.target.zc.className = 'BMap_Marker myPosition');
    }
    function maptilesloaded() {
        setTimeout(function () {
            map.addEventListener('moveend', moveendAddEvent)
            // map.addEventListener('clearoverlays', ()=>{
            //     console.log("clearoverlays")
            // })
        }, 2000)
        map.removeEventListener('tilesloaded', maptilesloaded);
    }
    function goARData() {
        goAMarket.hide();
        if (ScenicData[0] && ScenicData[0].points) {
            map.panTo(new BMap.Point(ScenicData[0].points.lng,ScenicData[0].points.lat));
            switch (TapIndex) {
                case 0:
                    ScenicData.map((item, index) => {
                        setMapCenter(item.points, index, item.SPIC, item['SNAME'])
                    });
                    break;
                case 1:
                    ScenicData.map((item, index) => {
                        setMapCenterWC(item.points, index, WCc);
                    });
                    break;
                case 2:
                    AllAttractions.map((item, index) => {
                        setMapCenterMPR(item, index);
                    })
                    playLineData.map((item, i) => {
                        setPlayLine(item.points, i);
                    });
                    break;
                case 3:
                    ScenicData.map((item, index) => {
                        var SPIC = item.FType === "出入口" ? exitsC : (item.FType === "停车场" ? carParkC : trafficC);
                        setMapCenterP(item.points, index, SPIC);
                    });
                    break;
                case 4:
                    ScenicData.map((item, index) => {
                        var SPIC = item.FType === "商店" ? MerchantC : DrinkingC;
                        setMapCenterDrink(item.points, index, SPIC);
                    });
                    break;
                case 5:
                    ScenicData.map((item, index) => {
                        setMapCenterTicket(item.points, index, TicketC);
                    })
                    break;
            }
        }
    }

    function setMapCenter(item, index, SPIC, AName) {
        //景点游玩
        var SPIC = SPIC ? SPIC : AcIcon;
        if (index == 0) {
            map.panTo(item);
        }

        var myIcon = new BMap.Icon(SPIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var size = new BMap.Size(0, h);
        var mk = new BMap.Marker(item, { icon: myIcon, offset: size });
        // console.log(map.getDistance(myPoint, item))
        var km = (Number((map.getDistance(myPoint, item)) || 0) / 1000).toFixed(2);
        var mm = (Number((map.getDistance(myPoint, item)) || 0)).toFixed(2);
        ScenicData[index]['km'] = km;
        ScenicData[index]['mm'] = mm;
        ScenicData[index]['points'] = item;
        ScenicData[index]['index'] = index;
        // console.log(myPoint, item,km,index,ScenicData[index].SNAME,ScenicData[index]['km']);
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;
        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            $(".app >div:not(.map)").hide();
            MapIndex = index;
            map.panTo(item);
            markerClick(index, mk.getPosition());
        });
        map.addOverlay(mk);
        var ANameDiv = document.createElement("div");
        var ANamespan = document.createElement("span");
        setTimeout(function () {
            // console.log(mk)
            mk.zc && (mk.zc.className = 'BMap_Marker attractionsMap');
            ANamespan.innerText = AName;
            ANameDiv.appendChild(ANamespan);
            ANameDiv.className = 'AName';
            mk.zc && (mk.zc.appendChild(ANameDiv));
        }, 20);
        countI++;
        if (index >= ScenicData.length - 1) {
            setAttractionsList();
        }
    }

    function setMapCenterWC(item, index, SPIC) {
        //WC
        if (index == 0) {
            map.panTo(item);
        }
        var myIcon = new BMap.Icon(SPIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var mk = new BMap.Marker(item, { icon: myIcon });
        ScenicData[index]['points'] = item;
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;
        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            MapIndex = index;
            clearWcIcon();
            var newWCO = new BMap.Icon(WCo, new BMap.Size(MapSize, MapSize));
            mk.setIcon(newWCO);
            markerWCClick(index);
        }, false);
        map.addOverlay(mk);
        setTimeout(function () {
            mk.zc && (mk.zc.className = 'BMap_Marker mapWC');
        }, 20);
    }


    function setMapCenterMPR(item, index) {
        //必玩
        let Point = item.points;
        if (index == 0) {
            map.panTo(Point);
            // map.setZoom(zoom);
        }
        var SPIC = item.SPIC ? item.SPIC : AcIcon;
        var myIcon = new BMap.Icon(SPIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var size = new BMap.Size(0, h);
        var mk = new BMap.Marker(Point, { icon: myIcon, offset: size });
        var km = item.km;
        AllAttractions[index]['index'] = index;
        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            $(".app >div:not(.map)").hide();
            MapIndex = index;
            map.panTo(item);
            markerClick(index, mk.getPosition());
        });
        map.addOverlay(mk);
        setTimeout(function () {
            var ANameDiv = document.createElement("div");
            var ANamespan = document.createElement("span");
            mk.zc && (mk.zc.className = 'BMap_Marker attractionsMap');
            ANamespan.innerText = item.SNAME;
            ANameDiv.appendChild(ANamespan);
            ANameDiv.className = 'AName';
            mk.zc && (mk.zc.appendChild(ANameDiv));
        }, 20);
        if (index >= AllAttractions.length - 1) {
            setPlayAttractionsList();
        }
    }
    function setPlayLine(item, index) {
        //必玩路线
        playLineData[index].points = item;
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;

        if (index >= playLineData.length - 1) {
            var pointsP = playLineData.map((item) => item.points);
            var polyline = new BMap.Polyline(pointsP, { strokeColor: "#1a9bff", strokeWeight: 4, strokeStyle: "dashed", strokeOpacity: 1, enableClicking: false });   //创建折线
            map.addOverlay(polyline);
        }
    }
    function setMapCenterP(item, index, SPIC) {
        //附属设施
        var km = (Number((map.getDistance(myPoint, item)) || 0) / 1000).toFixed(2);
        ScenicData[index]['km'] = km;
        ScenicData[index]['points'] = item;
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;
        if (index >= ScenicData.length - 1) {
            setAffiliatedList();
        }
    }

    function setMapCenterP2(Point, index, PIC, NewPIC, className) {
        //附属设施刷新
        if (index == 0) {
            map.panTo(Point);
        }
        var myIcon = new BMap.Icon(PIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var mk = new BMap.Marker(Point, { icon: myIcon });

        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            MapIndex = index;
            clearFacilityIcon();
            AllMarket.map(item => item.setTop(false));
            mk.setTop(true);
            var Icon2 = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
            $(".app >div:not(.map)").hide();
            mk.setIcon(Icon2);
            map.panTo(Point);
            markerWCClick(index);
        }, false);
        map.addOverlay(mk);
        AllMarket[index] = mk;
        setTimeout(function () {
            mk.zc && (mk.zc.className = 'BMap_Marker mapWC ' + className);
        }, 20);
    }

    function setMapCenterDrink(item, index, SPIC) {
        //商家
        var km = (Number((map.getDistance(myPoint, item)) || 0) / 1000).toFixed(2);
        ScenicData[index]['km'] = km;
        ScenicData[index]['points'] = item;
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;
        countI++;
        if (index >= ScenicData.length - 1) {
            setDrinkingList();
        }
    }


    function setMapCenterDrink2(Point, index, PIC, NewPIC, className) {
        //商家刷新
        if (index == 0) {
            map.panTo(Point);
        }
        var myIcon = new BMap.Icon(PIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var mk = new BMap.Marker(Point, { icon: myIcon });

        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            MapIndex = index;
            clearDrinkIcon();
            $(".app >div:not(.map)").hide();
            var Icon2 = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
            mk.setIcon(Icon2);
            AllMarket.map(item => item.setTop(false));
            mk.setTop(true);
            map.panTo(Point);
            markerWCClick(index);
        }, false);
        map.addOverlay(mk);
        AllMarket[index] = mk;
        setTimeout(function () {
            mk.zc && (mk.zc.className = 'BMap_Marker mapWC ' + className);
        }, 20);
    }

    function setMapCenterTicket(item, index, SPIC) {
        //售票处
        var km = (Number((map.getDistance(myPoint, item)) || 0) / 1000).toFixed(2);
        ScenicData[index]['km'] = km;
        ScenicData[index]['points'] = item;
        //获取 区域右上角
        if (getBsne.lat == "" || getBsne.lat < item.lat) getBsne.lat = item.lat;
        if (getBsne.lng == "" || getBsne.lng < item.lng) getBsne.lng = item.lng;
        //获取 区域左下角
        if (getBssw.lat == "" || getBssw.lat > item.lat) getBssw.lat = item.lat;
        if (getBssw.lng == "" || getBssw.lng > item.lng) getBssw.lng = item.lng;
        if (index >= ScenicData.length - 1) {
            setTicketList();
        }
    }

    function setMapCenterTicket2(Point, index, PIC, NewPIC, className) {
        //售票处刷新
        if (index == 0) {
            map.panTo(Point);
        }
        var myIcon = new BMap.Icon(PIC, new BMap.Size(MapSize, MapSize));
        var h = -(25 * (htmlWidth / 750));
        var mk = new BMap.Marker(Point, { icon: myIcon });

        mk.addEventListener("click", function (e) {
            e.domEvent.stopPropagation();
            MapIndex = index;
            clearTicketIcon();
            $(".app >div:not(.map)").hide();
            var Icon2 = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
            mk.setIcon(Icon2);
            map.panTo(Point);
            markerWCClick(index);
        }, false);
        map.addOverlay(mk);
        setTimeout(function () {
            mk.zc && (mk.zc.className = 'BMap_Marker mapWC ' + className);
        }, 20);
    }

    function markerClick(index) {
        //标点点击
        var data = (TapIndex == 2 ? AllAttractions : ScenicData)[index];
        var km = data.km;
        $(".app .footer >div").hide();
        $(".app .footer .AttractionsInfo").show();
        $(".app .footer .AttractionsInfo .info .img img").attr('src', data.SPIC);
        $(".app .footer .AttractionsInfo .info .text .name").text(data.SNAME);
        $(".app .footer .AttractionsInfo .info .text .introduction").text((data.SINTRODUCTION && data.SINTRODUCTION != "NULL") ? data.SINTRODUCTION : "无");
        $(".app .footer .AttractionsInfo .info .text .site .siteKm").text(km + 'km');
        $(".footer .AttractionsInfo .explain").attr('class', 'explain' + (((playBol && audioPlayIndex === index) || (autoNavPlay && autoPlayIndex === index)) ? " play" : (audioPlayIndex == index) ? " pause" : ""));
    }
    function markerWCClick(index, point) {
        //WC标点点击
        var data = ScenicData[index];
        $(".app .footer >div").hide();
        $(".app .footer .WCNavInfo").show();
        $(".app .footer .WCNavInfo .name").text(data.FNAME);
    }

    function setDom() {
        // $(".footer .sitePosition .ScenicName")
    }
    function setTitle(t) {
        document.title = t;
        var i = document.createElement('iframe');
        i.src = '//m.baidu.com/favicon.ico';//不可省略
        i.style.display = 'none';
        i.onload = function () {
            setTimeout(function () {
                i.remove();
            }, 9)
        }
        document.body.appendChild(i);
    }
    //景点详情
    function attractionShow() {
        $('.map').hide();
        var dataTap = (TapIndex == 2 ? AllAttractions : ScenicData);
        var data = dataTap[MapIndex];
        $(".app>.AttractionsInfo .img img").attr('src', data.SPIC)
        $(".app>.AttractionsInfo .autoControlbuttom .entry>span:first-child").text(MapIndex + 1);
        $(".app>.AttractionsInfo .autoControlbuttom .entry>span:last-child").text(dataTap.length);
        $(".app>.AttractionsInfo .introduction .txt").text((data.SINTRODUCTION && data.SINTRODUCTION != "NULL") ? data.SINTRODUCTION : "无");
        $(".app>.AttractionsInfo").show();
        if (MapIndex < 1) {
            $(".app>.AttractionsInfo .before i").attr('class', 'icon-beforeNo');
            $(".app>.AttractionsInfo .after i").attr('class', 'icon-after');
        } else if ((MapIndex > 0) && (MapIndex < dataTap.length - 1)) {
            $(".app>.AttractionsInfo .before i").attr('class', 'icon-before');
            $(".app>.AttractionsInfo .after i").attr('class', 'icon-after');
        } else if (MapIndex > dataTap.length - 2) {
            $(".app>.AttractionsInfo .after i").attr('class', 'icon-afterNo');
            $(".app>.AttractionsInfo .before i").attr('class', 'icon-before');
        }

        if ((playBol && audioPlayIndex == MapIndex)/* || (autoNavPlay && autoPlayIndex == MapIndex)*/) {
            $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-pause');
        } else {
            audioPlay()
        }
    }
    function setAttractionsList() {
        //景点列表
        var autoAudioIndex = null;
        var minKm = null;
        $(".AttractionsList .list").html('');
        var divs = ScenicData.filter((item) => (AttractionsSearch == '' || item.SNAME.indexOf(AttractionsSearch) > -1)).map(function (item, index) {
            //获取最小距离
            if (autoNavPlay && item.mm <= 40) {
                if ((minKm == null) || minKm > item.mm) {
                    autoAudioIndex = index;
                    minKm = item.mm;
                }
            }
            var div = $(`<div class="item">
                <div class="name">${item.SNAME}</div>
                <div class="km">${item.km}km</div>
            </div>`);

            div.click(function () {
                $(".AttractionsList").hide();
                MapIndex = item.index;
                markerClick(item.index);
                map.panTo(item.points);
                map.setZoom(zoom);
            });
            return div;
        }).sort((a, b) => parseFloat(a[0].lastElementChild.innerText) - parseFloat(b[0].lastElementChild.innerText));
        (divs[0])&&$(".app .footer .siteInfo .ScenicName").text(divs[0][0].children[0].innerText);
        (divs[0])&&$(".app .footer .siteInfo .distance").text(divs[0][0].children[1].innerText);
        $(".AttractionsList .list").append(divs);
        if(autoAudioIndex!=null&&autoAudioIndex>=0){
            var SWAV = ScenicData[autoAudioIndex].SWAV||"";
            var SWAV2 = $("#AttractionsAudio").attr('src');
            if (autoNavPlay &&(SWAV.length >0)&&($("#AttractionsAudio").get(0).ended||SWAV2 == '')&&(SWAV2 !=SWAV)) {
                autoAudioPlay(autoAudioIndex)
            }
        }
    }

    function setPlayAttractionsList() {
        //必玩景点列表
        var autoAudioIndex = null;
        var minKm = null;
        $(".AttractionsList .list").html('');
        var divs = AllAttractions.filter((item) => (AttractionsSearch == '' || item.SNAME.indexOf(AttractionsSearch) > -1)).map(function (item, index) {
            //获取最小距离
            if (autoNavPlay && item.mm <= 40) {
                if ((minKm == null) || minKm > item.mm) {
                    autoAudioIndex = index;
                    minKm = item.mm;
                    console.log('ok',index)
                }
            }
            var div = $(`<div class="item">
                <div class="name">${item.SNAME}</div>
                <div class="km">${item.km}km</div>
            </div>`);
            // console.log(item)
            div.click(function () {
                $(".AttractionsList").hide();
                MapIndex = item.index;
                markerClick(item.index, item.points);
                map.panTo(item.points);
                map.setZoom(zoom);
            });
            return div;
        }).sort((a, b) => parseFloat(a[0].lastElementChild.innerText) - parseFloat(b[0].lastElementChild.innerText));
        $(".AttractionsList .list").append(divs);
        $(".app .footer .siteInfo .ScenicName").text(divs[0][0].children[0].innerText);
        $(".app .footer .siteInfo .distance").text(divs[0][0].children[1].innerText);
        if(autoAudioIndex!=null&&autoAudioIndex>=0){
            var SWAV = AllAttractions[autoAudioIndex].SWAV||"";
            var SWAV2 = $("#AttractionsAudio").attr('src');
            if (autoNavPlay &&(SWAV.length >0)&&($("#AttractionsAudio").get(0).ended||SWAV2 == '')&&(SWAV2 !=SWAV)) {
                console.log('true')
                autoAudioPlay(autoAudioIndex)
            }
        }
    }

    function setDrinkingList(bol) {
        //商家列表
        var bol = bol || false;
        $(".DrinkList .list").html('');
        // console.log(ScenicData)
        var divs = ScenicData./*filter((item)=>(DrinkSearch == '' ||(item.FNAME||'').indexOf(DrinkSearch) > -1)).*/map(function (item, index) {
            if (item.FType == "商店" && merchantChecks.indexOf('storeS') == -1) {

            } else if (item.FType == "餐饮" && merchantChecks.indexOf('DrinkS') == -1) {

            } else {
                var km = (Number((map.getDistance(myPoint, item.points)) || 0) / 1000).toFixed(2);
                var div = $(`<div class="item">
                    <i class="${item.FType === "餐饮" ? 'icon-DrinkingC' : 'icon-MerchantC'}"></i>
                    <div class="name">${item.FNAME}</div>
                    <div class="km">${km}km</div>
                </div>`);

                div.click(function () {
                    $(".DrinkList").hide();
                    // MapIndex = index;
                    // markerClick(index,point);
                    $(".app >div:not(.map)").hide();
                    $(".footer>div.sitePositionDrink").show();
                    MapIndex = index;
                    map.panTo(item.points);
                    map.setZoom(zoom);
                    clearDrinkIcon();
                    markerWCClick(index);
                    var NewPIC = item.FType === "商店" ? MerchantO : DrinkingO;
                    var Icon2 = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
                    AllMarket[index].setIcon(Icon2)
                    AllMarket[index].setTop(true);
                });
                return div;
            }
        }).filter((item) => {
            var fname = $(item).find('.name').text();
            return (DrinkSearch == '' || (fname || '').indexOf(DrinkSearch) > -1)
        }).sort((a, b) => parseFloat(a[0].lastElementChild.innerText) - parseFloat(b[0].lastElementChild.innerText));
        $(".DrinkList .list").append(divs);
        if (!bol) {
            map.clearOverlays();
            AllMarket = [];
            ScenicData.map((item, index) => {
                if (!(DrinkSearch == '' || (item.FNAME || '').indexOf(DrinkSearch) > -1)) {
                } else if (item.FType == "商店" && merchantChecks.indexOf('storeS') == -1) {
                } else if (item.FType == "餐饮" && merchantChecks.indexOf('DrinkS') == -1) {
                } else {
                    var SPIC = item.FType === "商店" ? MerchantC : DrinkingC;
                    var NewPIC = item.FType === "商店" ? MerchantO : DrinkingO;
                    var className = item.FType === "商店" ? 'Merchant' : 'Drinking';
                    setMapCenterDrink2(item.points, index, SPIC, NewPIC, className);
                }
            })
        }
    }

    function setAffiliatedList(bol) {
        //附属设施列表
        var bol = bol || false;
        $(".AffiliatedList .list").html('');
        var divs = ScenicData.map(function (item, index) {
            if (item.FType == "停车场" && AffiliatedChecks.indexOf('carParkS') == -1) {

            } else if (item.FType == "出入口" && AffiliatedChecks.indexOf('exitS') == -1) {

            } else if (item.FType == "内部交通" && AffiliatedChecks.indexOf('trafficS') == -1) {

            } else {
                var km = (Number((map.getDistance(myPoint, item.points)) || 0) / 1000).toFixed(2);

                var div = $(`<div class="item">
                    <i class="${item.FType === "出入口" ? 'icon-exitsC' : (item.FType === "停车场" ? 'icon-carParkC' : 'icon-trafficC')}"></i>
                    <div class="name">${item.FNAME}</div>
                    <div class="km">${km}km</div>
                </div>`);

                div.click(function () {
                    $(".AffiliatedList").hide();
                    $(".footer>div.sitePositionAffiliated").show();
                    MapIndex = index;
                    markerWCClick(index);
                    map.panTo(item.points);
                    map.setZoom(zoom);
                    var NewPIC = item.FType === "出入口" ? exitsO : (item.FType === "停车场" ? carParkO : trafficO);
                    var Icon2 = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
                    AllMarket[index].setIcon(Icon2)
                    AllMarket[index].setTop(true);
                });
                return div;
            }
        }).sort((a, b) => parseFloat(a[0].lastElementChild.innerText) - parseFloat(b[0].lastElementChild.innerText));
        $(".AffiliatedList .list").append(divs);
        if (!bol) {
            map.clearOverlays();
            ScenicData.map((item, index) => {
                if (item.FType == "停车场" && AffiliatedChecks.indexOf('carParkS') == -1) {

                } else if (item.FType == "出入口" && AffiliatedChecks.indexOf('exitS') == -1) {

                } else if (item.FType == "内部交通" && AffiliatedChecks.indexOf('trafficS') == -1) {

                } else {
                    var SPIC = item.FType === "出入口" ? exitsC : (item.FType === "停车场" ? carParkC : trafficC);
                    var NewPIC = item.FType === "出入口" ? exitsO : (item.FType === "停车场" ? carParkO : trafficO);
                    var className = item.FType === "出入口" ? 'exits' : (item.FType === "停车场" ? 'carPark' : 'traffic');
                    setMapCenterP2(item.points, index, SPIC, NewPIC, className)
                }
            })
        }
    }

    function setTicketList(bol) {
        //售票处列表
        var bol = bol || false;
        // $(".TicketList .list").html('');
        // var divs = ScenicData.map(function (item, index) {
        //     if (item.FType == "售票处" && TicketChecks.indexOf('ticketS') == -1) {

        //     } else {
        //         var km = (Number((map.getDistance(myPoint, item.points)) || 0) / 1000).toFixed(2);

        //         var div = $(`<div class="item">
        //                 <i class="icon-TicketC"></i>
        //                 <div class="name">${item.FNAME}</div>
        //                 <div class="km">${km}km</div>
        //             </div>`);

        //         div.click(function () {
        //             $(".AffiliatedList").hide();
        //             $(".footer>div.sitePositionAffiliated").show();
        //             // MapIndex = index;
        //             // markerClick(index,point);
        //             map.panTo(item.points);
        //             map.setZoom(zoom);
        //         });
        //         return div;
        //     }
        // }).sort((a, b) => parseFloat(a[0].lastElementChild.innerText) - parseFloat(b[0].lastElementChild.innerText));
        // $(".TicketList .list").append(divs);
        if (!bol) {
            map.clearOverlays();
            ScenicData.map((item, index) => {
                var SPIC = TicketC;
                var NewPIC = TicketO;
                var className = item.FType === "售票处" ? 'Ticket' : '';
                setMapCenterTicket2(item.points, index, SPIC, NewPIC, className);
            })
        }
    }


    //解说播放
    function audioPlay() {
        var data = (TapIndex == 2 ? AllAttractions : ScenicData)[MapIndex];
        $("#AttractionsAudio").get(0).pause();
        clearInterval(audioSetItme);
        playBol = true;
        if (data.SWAV) {
            // console.log(playBol,autoNavPlay,audioPlayIndex,autoPlayIndex,MapIndex)
            if ((playBol && audioPlayIndex == MapIndex) || (autoNavPlay && autoPlayIndex == MapIndex)) {
                $("#AttractionsAudio").get(0).play();
            } else {
                audioPlayIndex = MapIndex;
                $("#AttractionsAudio").attr('src', data.SWAV);
                $("#AttractionsAudio").get(0).play();
            }

            $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-pause')
            $(".footer .AttractionsInfo .explain").attr('class', 'explain play');
            // console.log('play', data)
            audioSetItme = setInterval(function () {
                var duration = $("#AttractionsAudio").get(0).duration || 0,
                    durationTxt = (parseInt(duration / 60) < 10 ? '0' : '') + parseInt(duration / 60) + ':' + (parseInt(duration % 60) < 10 ? '0' : '') + (parseInt(duration % 60)),
                    currentTime = $("#AttractionsAudio").get(0).currentTime || 0,
                    currentTimeTxt = (parseInt(currentTime / 60) < 10 ? '0' : '') + parseInt(currentTime / 60) + ':' + (parseInt(currentTime % 60) < 10 ? '0' : '') + (parseInt(currentTime % 60)),
                    ended = $("#AttractionsAudio").get(0).ended,
                    left = ((currentTime / duration) * 100).toFixed(2);
                $('div.AttractionsInfo > div.audioPack > div.autoControlStrip > div.tiem > span:first-child').text(currentTimeTxt);
                $('div.AttractionsInfo > div.audioPack > div.autoControlStrip > div.tiem > span:nth-child(2)').text(durationTxt);
                $('div.AttractionsInfo > div.audioPack > div.autoControlStrip > div.strip .s-position').css('left', left + '%');
                $('div.AttractionsInfo > div.audioPack > div.autoControlStrip > div.strip .s-ac-hr').css('width', left + '%');
                if (ended) {
                    clearInterval(audioSetItme);
                    playBol = false;
                    $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-play1');
                }

            }, 100)
        } else {
            audioPause();
        }
    }
    //播放停止
    function audioPause() {
        playBol = false;
        autoPlayIndex = null;
        audioSetItme && clearInterval(audioSetItme);
        $("#AttractionsAudio").get(0).pause();
        $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-play1');
        $(".footer .AttractionsInfo .explain").attr('class', 'explain');
    }
    //智能导游播放
    function autoAudioPlay(index) {
        var dataTap = (TapIndex == 2 ? AllAttractions : ScenicData);
        // console.log(TapIndex )
        if (dataTap.length <= index) {
            autoNavPlay = false;
            return;
        }
        // console.log(index, data)
        // playBol= true;
        $(".footer .AttractionsInfo .explain").attr('class', 'explain' + (((playBol && audioPlayIndex == MapIndex) || (autoNavPlay && autoPlayIndex == MapIndex)) ? " play" : ""));
        $("#AttractionsAudio").get(0).pause();
        if (!autoNavPlay) {
            $("#AttractionsAudio").get(0).pause();
            return;
        }

        autoPlayIndex = index;
        var data = dataTap[autoPlayIndex];

        if (data.SWAV.length > 0) {
            $("#AttractionsAudio").attr('src', data.SWAV);
            $("#AttractionsAudio").get(0).play();
            $(".app>.AttractionsInfo .audioPack .autoControlStrip .play i").attr('class', 'icon-pause')
            // $("#AttractionsAudio").get(0).addEventListener('error', function () {
            // console.log('error')
            // autoAudioPlay(autoPlayIndex + 1);
            // autoNavPlay = false;
            // });

        } else {
            // autoAudioPlay(autoPlayIndex + 1);
            // autoNavPlay = false;
            audioPause();
        }
    }


    function clearWcIcon(index) {
        map.getOverlays().map((item) => {
            if (item.zc && item.zc.className.indexOf('mapWC') > 0) {
                var newWCc = new BMap.Icon(WCc, new BMap.Size(MapSize, MapSize));
                item.setIcon(newWCc)
            }
        })
    }

    function clearFacilityIcon(index) {
        map.getOverlays().map((item) => {
            var className = item.zc ? item.zc.className : '';
            if (className.indexOf('mapWC') > 0) {
                var classT = className.split(" ")[2];
                var NewPIC = classT === "exits" ? exitsC : (classT === "carPark" ? carParkC : trafficC);
                var newWCc = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
                item.setIcon(newWCc)
            }
        })
    }

    function clearDrinkIcon(index) {
        map.getOverlays().map((item) => {
            var className = item.zc ? item.zc.className : '';
            if (className.indexOf('mapWC') > 0) {
                var classT = className.split(" ")[2];
                var NewPIC = classT === "Merchant" ? MerchantC : DrinkingC;
                var newWCc = new BMap.Icon(NewPIC, new BMap.Size(MapSize, MapSize));
                item.setIcon(newWCc)
            }
        })
    }

    function clearTicketIcon(index) {
        map.getOverlays().map((item) => {
            var className = item.zc ? item.zc.className : '';
            if (className.indexOf('mapWC') > 0) {
                // var classT = className.split(" ")[2];
                var newWCc = new BMap.Icon(TicketC, new BMap.Size(MapSize, MapSize));
                item.setIcon(newWCc)
            }
        })
    }
    function tipsShow(desc) {
        $(".tips").show()
        $(".tips span").text(desc);
        setTimeout(() => {
            $(".tips").hide()
        }, 2000)
    }
    // function getWeixinopenid(){
    //     var code = localStorage.code||GetQueryString('code');
    //     if(!(code&&code.length>0))return;
    //     //获取openid
    //     request(weixinopenid+"?code="+code, {
    //         code
    //     }, (result)=>{
    //         openid = result.split("\n")[0].replace(/\s/g,'');
    //     }, (result)=>{
    //         // console.log('getWeixinopenid:error')
    //     },"POST")
    // }
    function getWXCode() {
        request(weixinpay,{openid,total_fee:AttractionsPrice},(result)=>{
            // console.log(result.split("\n"))
            var data = JSON.parse(result.split("\n")[0]);
            wxPayParams = {
                appId:data.appId,
                timeStamp:data.timeStamp,
                nonceStr:data.nonceStr,
                package:data.package,
                signType:data.signType,
                paySign:data.paySign,
            }
            // console.log("wxPayParams",JSON.parse(JSON.stringify(wxPayParams)))
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady();
            }
        },(result)=>{

        },"get");
        // request(payRequest, {
        //     goodName: AID,
        //     goodPrice: AttractionsPrice
        // }, (result) => {
        //     // console.log('result',result.replace(/^\s*|\s*$/g,""))
        //     console.log('loadXml', loadXML(result.replace(/^\s*|\s*$/g, "")));
        //     var dataDom = loadXML(result.replace(/^\s*|\s*$/g, ""));
        //     if(!(dataDom.getElementsByTagName('appid')[0]&&dataDom.getElementsByTagName('appid')[0].innerHTML))return ;
        //     var retcode = dataDom.getElementsByTagName('retcode')[0].innerHTML;
        //     var retmsg = dataDom.getElementsByTagName('retmsg')[0].innerHTML;
        //     var noncestr = dataDom.getElementsByTagName('noncestr')[0].innerHTML;
        //     var packageA = dataDom.getElementsByTagName('package')[0].innerHTML;
        //     var partnerid = dataDom.getElementsByTagName('partnerid')[0].innerHTML;
        //     var prepayid = dataDom.getElementsByTagName('prepayid')[0].innerHTML;
        //     var sign = dataDom.getElementsByTagName('sign')[0].innerHTML;
        //     var timestamp = dataDom.getElementsByTagName('timestamp')[0].innerHTML;
        //     var appid = dataDom.getElementsByTagName('appid')[0].innerHTML;

        //     wxPayParams = {
        //         dataDom,
        //         retcode,
        //         retmsg,
        //         noncestr,
        //         packageA,
        //         partnerid,
        //         prepayid,
        //         sign,
        //         timestamp,
        //         mch_id: "1433616402",
        //         appId: appid
        //     };
        //    
        // }, (result) => {
        //     console.log('result Error', result)
        // }, "post")
    }
    function onBridgeReady() {
        // window.location = "https://api.mch.weixin.qq.com/pay/unifiedorder"+
        //                     "?appId="+wxPayParams.appId+
        //                     "&mch_id="+wxPayParams.appId+
        //                     "&nonce_str="+wxPayParams.nonceStr+
        //                     "&sign="+wxPayParams.sign+
        //                     "&sign_type=MD5"+
        //                     "&body=e景游-"+ScenicName+
        //                     "&out_trade_no="+prepayid+
        //                     "&total_fee="+AttractionsPrice+
        //                     "&trade_type="+"JSAPI"+
        //                     "&product_id="+AID+
        //                     "&mch_id="+wxPayParams.appId;
        // wx.config(
        //    {    debug: true,
        //         appId:wxPayParams.appId,
        //         timeStamp:wxPayParams.timeStamp,
        //         nonceStr:wxPayParams.nonceStr,
        //         signature:wxPayParams.sign,
        //         jsApiList:["chooseWXPay"]
        //         // "signType":"MD5",
        //         // "paySign":wxPayParams.sign,
        //         // success: function (res) {
        //         //     alert("支付成功");
        //         // }
        //     }
        // );
        // wx.chooseWXPay({
        //     appId:wxPayParams.appId,
        //     timestamp: wxPayParams.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        //     nonceStr: wxPayParams.nonceStr, // 支付签名随机串，不长于 32 位
        //     package: wxPayParams.packageA, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        //     signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        //     paySign: wxPayParams.sign, // 支付签名
        //     success: function (res) {
        //         // 支付成功后的回调函数
        //         alert("支付成功")
        //     }
        // });
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId": wxPayParams.appId,    //公众号名称，由商户传入
                "timeStamp": wxPayParams.timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr": wxPayParams.nonceStr, //随机串
                "package": wxPayParams.package,
                "signType": wxPayParams.signType||"MD5",         //微信签名方式：
                "paySign": wxPayParams.paySign//微信签名
            },
            function (res) {
                WeixinJSBridge.log(res.err_msg);
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    tipsShow("购买成功请留意短信");
                }
            }
        );

    }

    var loadXML = function (xmlString) {
        var xmlDoc = null;
        //判断浏览器的类型
        //支持IE浏览器
        if (!window.DOMParser && window.ActiveXObject) {   //window.DOMParser 判断是否是非ie浏览器
            var xmlDomVersions = ['MSXML.2.DOMDocument.6.0', 'MSXML.2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
            for (var i = 0; i < xmlDomVersions.length; i++) {
                try {
                    xmlDoc = new ActiveXObject(xmlDomVersions[i]);
                    xmlDoc.async = false;
                    xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串
                    break;
                } catch (e) {
                }
            }
        }
        //支持Mozilla浏览器
        else if (window.DOMParser && document.implementation && document.implementation.createDocument) {
            try {
                /* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。
                 * 要使用 DOMParser，使用不带参数的构造函数来实例化它，然后调用其 parseFromString() 方法
                 * parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型
                 * 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意，不支持 "text/html"。
                 */
                var domParser = new DOMParser();
                xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
            } catch (e) {
            }
        }
        else {
            return null;
        }

        return xmlDoc;
    }

})